import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { useRobotStore } from '@/stores/robotStore';
import { createROSClient } from '@/composables/ros/rosClient';
import { createCmdVelBinder } from '@/composables/ros/cmdVelService';
import { createSensorService } from '@/composables/ros/sensorService';
// import { createCameraService } from '@/composables/ros/cameraService'; // HTTP流模式不再需要
import { PUBLISH_THROTTLE_MS } from '@/constants/ros';

export function useROSConnection() {
  const robotStore = useRobotStore();
  
  // 简化状态管理
  const connectionTimeout = ref(null);
  const throttleTimer = ref(null);
  const latestCommand = ref({ x: 0, y: 0, w: 0, dirty: false });
  const isConnecting = ref(false);

  // 服务实例
  let cmdVelBinder = null;
  let sensorService = null;
  // let cameraService = null; // HTTP流模式不再需要

  // 统一资源清理函数
  const cleanup = () => {
    stopThrottleLoop();
    if (connectionTimeout.value) {
      clearTimeout(connectionTimeout.value);
      connectionTimeout.value = null;
    }
    try { 
      sensorService && sensorService.unsubscribeAll(); 
    } catch (e) { 
      robotStore.addLog(`传感器取消订阅失败: ${e?.message || e}`, 'warning'); 
    }
    // HTTP流模式不再需要摄像头服务清理
    cmdVelBinder = null;
    sensorService = null;
    // cameraService = null; // HTTP流模式不再需要
  };

  // 连接方法
  const connect = (isAutoConnect = false) => {
    if (isConnecting.value) {
      robotStore.addLog('正在建立连接，请稍候...', 'warning');
      return;
    }
    if (robotStore.isConnected && robotStore.ros) {
      robotStore.addLog('已连接，无需重复连接', 'info');
      return;
    }
    if (!robotStore.robotIp || !robotStore.robotPort) {
      robotStore.addLog('请输入有效的IP地址和端口', 'error');
      return;
    }
    
    const url = robotStore.connectionUrl;
    const logMessage = isAutoConnect ? 
      `🔄 自动连接中: ${url}...` : 
      `正在连接到 ${url}...`;
    
    robotStore.addLog(logMessage, 'warning');
    robotStore.addLog(`连接URL: ${url}`, 'info');
    
    isConnecting.value = true;
    const ros = createROSClient(url, {
      onConnection: onConnected,
      onError,
      onClose: onDisconnected
    });
    robotStore.setROS(ros);
    
    // 设置连接超时
    connectionTimeout.value = setTimeout(() => {
      if (!robotStore.isConnected) {
        const timeoutMessage = isAutoConnect ? 
          '⏰ 自动连接超时，请手动连接或检查网络状态' : 
          '连接超时，请检查网络和机器人状态';
        robotStore.addLog(timeoutMessage, 'error');
        
        // 如果是自动连接失败，清理连接对象
        if (isAutoConnect && ros) {
          ros.close();
          robotStore.setROS(null);
        }
      }
    }, 10000);
  };

  // 连接成功回调
  const onConnected = async () => {
    isConnecting.value = false;
    robotStore.setConnectionStatus(true);
    robotStore.addLog('成功连接到机器人！', 'success');
    
    // 等待Vue状态更新完成
    await nextTick();
    
    // 初始化服务
    cmdVelBinder = createCmdVelBinder(robotStore.ros, robotStore.addLog.bind(robotStore));
    sensorService = createSensorService(robotStore.ros, {
      onTemperature: (t) => robotStore.updateSensorData(t, robotStore.humidity),
      onHumidity: (h) => {
        robotStore.updateSensorData(robotStore.temperature, h);
        robotStore.addLog(`收到湿度数据: ${Number(h).toFixed(1)}%`, 'success');
      },
      onBattery: (p) => robotStore.updateBattery(p),
      addLog: robotStore.addLog.bind(robotStore)
    });

    // HTTP流模式不再需要摄像头服务初始化
    // cameraService = createCameraService(robotStore.ros, {
    //   addLog: robotStore.addLog.bind(robotStore)
    // });

    // 订阅传感器
    sensorService.subscribeAll();
    
    // HTTP流模式不再需要订阅摄像头话题
    // cameraService.subscribeToCamera();
    
    // 检测ROS环境并绑定cmd_vel
    robotStore.addLog('🔍 正在检测ROS环境...', 'info');
    robotStore.addLog('🤖 检测到 ROS2 环境', 'success');
    await findBestCmdVelTopic();

    // 再次等待Vue状态更新完成，确保cmdVelBinder已正确初始化
    await nextTick();
    
    // 额外等待一小段时间，确保所有异步操作完成
    await new Promise(resolve => setTimeout(resolve, 100));
    
    // 启动节流循环
    startThrottleLoop();
  };

  // 连接错误回调
  const onError = (error) => {
    robotStore.addLog(`连接错误: ${error}`, 'error');
    robotStore.setConnectionStatus(false);
    isConnecting.value = false;
  };

  // 连接断开回调
  const onDisconnected = () => {
    isConnecting.value = false;
    robotStore.setConnectionStatus(false);
    robotStore.addLog('与机器人的连接已断开', 'warning');
    
    // 清理资源
    robotStore.setROS(null);
    cleanup();
    
    // 重置传感器数据
    robotStore.updateSensorData(0, 0);
  };

  // 断开连接
  const disconnect = () => {
    if (robotStore.ros) {
      publishVelocity(0, 0);
      robotStore.ros.close();
      robotStore.addLog('主动断开连接', 'warning');
    }
  };

  // 查找最佳cmd_vel话题
  const findBestCmdVelTopic = async () => {
    if (!cmdVelBinder) return;
    
    // 确保cmdVelBinder完全初始化后再进行话题绑定
    await nextTick();
    cmdVelBinder.detectAndBind();
  };

  // 发布速度（写入节流缓冲区）
  const publishVelocity = (linear, angular) => {
    publishVelocityWithY(linear, 0, angular);
  };

  // 发布带Y轴的速度
  const publishVelocityWithY = (linearX, linearY, angular) => {
    // 更新UI显示速度
    robotStore.updateSpeed(
      Math.sqrt(linearX * linearX + linearY * linearY),
      angular
    );
    
    // 写入最新指令，节流循环中统一发布
    latestCommand.value = { x: linearX, y: linearY, w: angular, dirty: true };
  };

  // 启动节流循环
  const startThrottleLoop = () => {
    if (throttleTimer.value) return;
    
    // 确保所有必要的状态都已准备好
    if (!robotStore.isConnected || !robotStore.ros) {
      robotStore.addLog('⚠️ 无法启动节流循环：连接状态异常', 'warning');
      return;
    }
    
    robotStore.addLog('🚀 启动速度命令节流循环', 'info');
    
    throttleTimer.value = setInterval(() => {
      if (!robotStore.isConnected || !robotStore.ros) return;
      if (!latestCommand.value.dirty) return;
      
      if (!cmdVelBinder) {
        cmdVelBinder = createCmdVelBinder(robotStore.ros, robotStore.addLog.bind(robotStore));
        cmdVelBinder.detectAndBind();
      }
      
      const { x, y, w } = latestCommand.value;
      try {
        if (cmdVelBinder) {
          cmdVelBinder.publishTwist(x, y, w);
        }
      } catch (error) {
        robotStore.addLog(`❌ 发布失败: ${error?.message || error}`, 'error');
      }
      latestCommand.value.dirty = false;
    }, PUBLISH_THROTTLE_MS);
  };

  const stopThrottleLoop = () => {
    if (throttleTimer.value) {
      clearInterval(throttleTimer.value);
      throttleTimer.value = null;
    }
  };

  // 自动连接
  const autoConnect = () => {
    if (!robotStore.robotIp || !robotStore.robotPort) {
      robotStore.addLog('自动连接失败：IP地址或端口未配置', 'error');
      return;
    }
    
    robotStore.addLog('🔄 页面加载，正在尝试自动连接...', 'info');
    connect(true);
  };

  // 生命周期钩子
  onMounted(() => {
    // 页面加载时自动尝试连接一次
    autoConnect();
  });

  onUnmounted(() => {
    // 清理资源
    cleanup();
  });

  // HTTP流模式不再需要设置摄像头canvas
  // const setupCameraCanvas = (canvas) => {
  //   if (cameraService && canvas) {
  //     cameraService.setCanvas(canvas);
  //   }
  // };

  return {
    // 方法
    connect,
    disconnect,
    publishVelocity,
    publishVelocityWithY,
    autoConnect,
    // setupCameraCanvas, // HTTP流模式不再需要
    
    // 连接状态
    isConnected: robotStore.isConnected,
    robotIp: robotStore.robotIp,
    robotPort: robotStore.robotPort,
    
    // 计算属性
    selectedCmdVelName: () => cmdVelBinder?.selected || '/cmd_vel'
  };
}
